package cn.hsa.fqz.task.controller;

import cn.hsa.fqz.common.enums.FileType;
import cn.hsa.fqz.handler.base.BaseController;
import cn.hsa.fqz.task.controller.vo.TTaskWorkReportDetailVO;
import cn.hsa.fqz.task.controller.vo.TTaskWorkReportQueryVO;
import cn.hsa.fqz.task.entity.TTaskWorkReport;
import cn.hsa.fqz.task.entity.TTaskWorkReportDetailAttachment;
import cn.hsa.fqz.task.enums.UserCategoryEnums;
import cn.hsa.fqz.task.service.TSysFileAccessoryService;
import cn.hsa.fqz.task.service.TaskReportService;
import cn.hsa.fqz.task.service.dto.LoginUserDTO;
import cn.hsa.fqz.task.service.dto.TTaskWorkReportDetailDTO;
import cn.hsa.fqz.util.UserRegionUtils;
import cn.hsa.hsaf.core.framework.context.HsafContextHolder;
import cn.hsa.hsaf.core.framework.util.CurrentUser;
import cn.hsa.hsaf.core.framework.util.PageResult;
import cn.hsa.hsaf.core.framework.web.WrapperResponse;
import cn.hsa.hsaf.core.fsstore.FSEntity;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.io.IOUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.List;

/**
 * @Description TODO
 * @ClassName TaskReportController
 * @Author Liu.Jun
 * @Create 2023-12-11 11:14
 * @Version 1.0.0
 */
@Slf4j
@Api(value = "专项整治工作上报管理", tags = "专项整治工作上报管理")
@RestController
@RequestMapping("/task/report")
public class TaskReportController extends BaseController {

    @Autowired
    private TaskReportService taskReportService;

    @Autowired
    private TSysFileAccessoryService sysFileAccessoryService;

    @ApiOperation(value = "工作任务列表", notes = "工作任务列表")
    @GetMapping("/list")
    public WrapperResponse<List<TTaskWorkReport>> getReportByYearmutil(@RequestParam(value = "yearmutil",required = false)String yearmutil){
        List<TTaskWorkReport> reports = taskReportService.getReportByYearmutil(yearmutil);
        return WrapperResponse.success(reports);
    }

    @ApiOperation(value = "工作任务填报列表", notes = "工作任务填报列表")
    @PostMapping("/details/list")
    public WrapperResponse<PageResult<TTaskWorkReportDetailDTO>> list(@RequestBody TTaskWorkReportQueryVO query) {
        CurrentUser currentUser = HsafContextHolder.getContext().getCurrentUser();
        LoginUserDTO loginUser = super.getLoginUser(currentUser);
        UserCategoryEnums enums = UserRegionUtils.getUserCateEnumByAscm(loginUser.getRegion());
        if(enums == UserCategoryEnums.PROVINCE){
            query.getCondition().setRegion(loginUser.getRegion());
        }
        PageResult<TTaskWorkReportDetailDTO> result = taskReportService.getPageDetailByCondition(query);
        return WrapperResponse.success(result);
    }

    @ApiOperation(value = "新增工作填报", notes = "新增工作填报")
    @PostMapping("/details/add")
    public WrapperResponse<Boolean> addReportDetails(@RequestBody TTaskWorkReportDetailVO vo){
        CurrentUser currentUser = HsafContextHolder.getContext().getCurrentUser();
        LoginUserDTO dto = getLoginUser(currentUser);
        vo.setCreateBy(dto.getUid());
        vo.setCreateByName(dto.getUname());
        vo.setRegion(dto.getRegion());
        Boolean result = taskReportService.addRptDetail(vo);
        return WrapperResponse.success(result);
    }

    @ApiOperation(value = "工作任务填报列表", notes = "工作任务填报列表")
    @DeleteMapping("/details/delete")
    public WrapperResponse<Boolean> addReportDetails(@RequestParam("reportDetailId")Integer reportDetailId){
        CurrentUser currentUser = HsafContextHolder.getContext().getCurrentUser();
        LoginUserDTO dto = getLoginUser(currentUser);
        WrapperResponse<Boolean> result = taskReportService.deleteRptDetail(dto,reportDetailId);
        return result;
    }

    @ApiOperation(value = "文件上传", notes = "文件上传")
    @PostMapping("/file/upload")
    public WrapperResponse<String> uploadFile(@RequestParam("reportId") String reportId,
                                              @RequestParam MultipartFile file) {
        /*if(file.getSize()>20*1024*1024){
            return WrapperResponse.error(500, "超过文件大小上限", null);
        }*/
        CurrentUser currentUser = HsafContextHolder.getContext().getCurrentUser();
        LoginUserDTO dto = super.getLoginUser(currentUser);
        try {
            String accessoryId =  DigestUtils.md5Hex(reportId+currentUser.getUserAcct());
            return WrapperResponse.success(sysFileAccessoryService.upload(accessoryId, FileType.MED,dto, file));
        } catch (Exception e) {
            e.printStackTrace();
            return WrapperResponse.error(500, "文件上传失败", e.getMessage());
        }
    }

    @ApiOperation(value = "文件下载", notes = "文件下载")
    @GetMapping("/file/download")
    public void downloadFile(HttpServletResponse response, @RequestParam("fileNo")String fileNo, @RequestParam("detailId")Integer detailId) {
        try {
            TTaskWorkReportDetailAttachment attachmentDO = taskReportService.getAttachmentByDetailAndFileNo(fileNo, detailId);
            response.setHeader("Content-Type", "application/octet-stream");
            response.setContentType("application/octet-stream");
            String filenameEncoder = "";
            String fileName = attachmentDO.getFileName();
            filenameEncoder = URLEncoder.encode(fileName, "utf-8");
            response.setHeader("Content-Disposition", "attachment;filename=" + filenameEncoder);
            InputStream inputStream = null;
            FSEntity fsEntity = sysFileAccessoryService.get(null,FileType.MED,fileName);
            inputStream = fsEntity.getInputstream();
            OutputStream out = null;
            try {
                out = response.getOutputStream();
                IOUtils.copy(inputStream, out);
                out.flush();
            } finally {
                if (out != null) {
                    out.close();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
